<?php

namespace app\base\controller\api;

use app\base\model\MemberPlans;
use app\base\service\MemberService;
use think\admin\Controller;
use app\base\service\TokenService;
use think\admin\model\SystemUser;
use think\admin\service\CaptchaService;


/**
 * 登陆
 * Class Login
 * @package app\store\controller
 */
class Login extends Controller
{


    /**
     * 商店登录入口
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function index()
    {
        $data = $this->request->post();
        $this->_vali([
            'username.require' => '登录账号不能为空!',
            'password.require' => '登录密码不能为空!',
            'captcha.require'   => '图形验证码不能为空!',
            'uniqid.require'   => '图形验证标识不能为空!',
        ],$data);
        if (!CaptchaService::instance()->check($data['captcha'], $data['uniqid'])) {
            $this->error('图形验证码验证失败，请重新输入!');
        }
        /*! 用户信息验证 */
        $map = ['username' => $data['username'], 'is_deleted' => '0'];
        $user = $this->app->db->name('ai_user')
            ->field('id,usertype,username,nickname,status,password,api_config_type')
            ->where($map)
            ->order('id desc')
            ->find();

        if (empty($user)) {
            $this->error('登录账号或密码错误，请重新输入!');
        }
        if (empty($user['status'])) {
            $this->error('账号已经被禁用，请联系管理员!');
        }
        if ($user['password'] !== md5($data['password'])) {
            $this->error('登录账号或密码错误，请重新输入!');
        }

        $this->app->db->name('ai_user')->where(['id'=>$user['id']])->inc('login_num')->update([
            'login_at'=>date('Y-m-d H:i:s'),
            'login_ip'=>$this->request->ip(),
        ]);
        $token = TokenService::instance()->token_create($user['id']);

        TokenService::instance()->token_set($user['id'], $token);
        unset($user['password']);
        $user['token'] = $token;
        $this->success("登录成功",$user);
    }


    /**
     * APP登录入口
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function app_login()
    {
        $data = $this->request->post();
        $this->_vali([
            'username.require' => '登录账号不能为空!',
            'password.require' => '登录密码不能为空!',
            'device_name.require' => '设备信息不能为空!'
        ],$data);

        /*! 用户信息验证 */
        $map = ['username' => $data['username'], 'is_deleted' => '0'];
        $user = $this->app->db->name('ai_user')
            ->field('id,usertype,username,nickname,status,password,jc_devices,jl_devices')
            ->where($map)
            ->order('id desc')
            ->find();

        if (empty($user)) {
            $this->error('登录账号或密码错误，请重新输入!');
        }
        if (empty($user['status'])) {
            $this->error('账号已经被禁用，请联系管理员!');
        }
        if ($user['password'] !== md5($data['password'])) {
            $this->error('登录账号或密码错误，请重新输入!');
        }

        $this->app->db->name('ai_user')->where(['id'=>$user['id']])->inc('login_num')->update([
            'login_at'=>date('Y-m-d H:i:s'),
            'login_ip'=>$this->request->ip(),
        ]);
        $device = $this->app->db->name('ai_device')->where(['device_name'=>$data['device_name'],'user_id'=>$user['id']])->find();
        if(empty($device)){
            if($user['id']!=10000){
                $device_num = $this->app->db->name('ai_device')->where(['user_id'=>$user['id']])->count();
                if($device_num>($user['jl_devices']+$user['jc_devices'])){
                    $this->error('设备已满,请升级会员或购买设备加量包');
                }
            }


            $group_id = $this->app->db->name("ai_device_group")->where(['user_id'=>$user['id']])->order('id asc')->value("id");
            if(empty($group_id)){
                $group_id = $this->app->db->name("ai_device_group")->insertGetId([
                    'user_id'=>$user['id'],
                    'name'=>'默认分组',
                ]);
            }
            $device_id = $this->app->db->name('ai_device')->insertGetId([
                'device_name'=>$data['device_name'],
                'user_id'=>$user['id'],
                'login_at'=>date('Y-m-d H:i:s'),
                'login_ip'=>$this->request->ip(),
                'group_id'=>$group_id,
            ]);
        }else{
            $device_id = $device['id'];
            $this->app->db->name('ai_device')->where(['id'=>$device_id])->update([
                'login_at'=>date('Y-m-d H:i:s'),
                'login_ip'=>$this->request->ip(),
            ]);
        }
        $user['device_id'] = $device_id;
        $token = TokenService::instance()->token_create($user['id']);

        TokenService::instance()->token_set($user['id'], $token);
        unset($user['password']);
        $user['token'] = $token;
        $this->success("登录成功",$user);
    }

    //用户注册
    public function register()
    {
        $data = $this->request->post();
        $this->_vali([
            'username.require' => '用户名不能为空!',
            'password.require' => '密码不能为空!',
            'contact_phone.require' => '手机号不能为空!',
            'captcha.require'   => '图形验证码不能为空!',
            'uniqid.require'   => '图形验证标识不能为空!',
        ],$data);
        if (!CaptchaService::instance()->check($data['captcha'], $data['uniqid'])) {
            $this->error('图形验证码验证失败，请重新输入!');
        }
        $data['nickname'] = $data['username'];

        $user = $this->app->db->name('ai_user')->where(['username'=>$data['username']])->find();
        if(!empty($user)){
            $this->error('用户名已存在');
        }
        $user = $this->app->db->name('ai_user')->where(['contact_phone'=>$data['contact_phone']])->find();
        if(!empty($user)){
            $this->error('手机号已存在');
        }
        $data['password'] = md5($data['password']);
        unset($data['captcha']);
        unset($data['uniqid']);
        $data['status'] = 1;
        $expire_date = date('Y-m-d H:i:s',strtotime('+3 days'));
        $data['expire_date'] = $expire_date;
        $data['member_plans_id'] = 0;
        $id = $this->app->db->name('ai_user')->insertGetId($data);
        if(empty($id)){
            $this->error('注册失败');
        }
        $fx_code = md5($id."LYZK2025!!");
        $this->app->db->name('ai_user')->where(['id'=>$id])->update([
            'fx_code'=>$fx_code,
        ]);
        $package_id = 0;
        $package = MemberPlans::mQuery()->where(['id'=>$package_id])->find();
        $order_id=  MemberService::instance()->createOrder($id,$package_id,1,1,2);
        $this->app->db->name('member_bean_records')->insert([
            'user_id' => $id,
            'package_id' => $package_id,
            'source_type' => 1,
            'total_beans' => $package['beans'],
            'remaining_beans' => $package['beans'],
            'expire_date' => $expire_date,
            'order_id' => $order_id,
            'create_type'=>2
        ]);
        $this->success("注册成功");
    }


    /**
     * 生成验证码
     * @return void
     */
    public function captcha()
    {

        $image = CaptchaService::instance()->initialize();
        $captcha = ['image' => $image->getData(), 'uniqid' => $image->getUniqid()];
        $this->success('生成验证码成功', $captcha);
    }

    //获取app版本信息
    public function app_version(){
        $data = [
            "code"=>8,
            'name'=>'2.8.0',
            'description'=>"1. 提升app运行效率及稳定性\n 2. 修复已知问题\n 3. 新增单视频多平台发布",
            'downloadUrl'=>"http://dev.blueant.pro/ziyuan/蓝蚁智控2.8.apk",
        ];
        $this->success("获取成功",$data);
    }


}
